package com.guaoran.study.odps;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.IOException;
import java.util.Properties;

/**
 * @author : gu cheng
 * @description : ftp
 * @date : 2021/10/14 18:57
 */
public class FtpDemo {

    public static void main(String[] args) throws IOException, JSchException {
//        URL url = new URL( "ftp://syrw:Sy2021$c@172.26.108.218:21/dpaas/javaa.txt" );
//        PrintWriter pw = new PrintWriter(url.openConnection().getOutputStream());
//        pw.write( " guaoran test " );
//        pw.flush();
//        pw.close();


        FtpDataSourceConfigDTO configDTO = new FtpDataSourceConfigDTO();
        configDTO.setIp("172.26.108.218");
        configDTO.setPort(21);
        configDTO.setUsername("syrw");
        configDTO.setPassword("Sy2021$c");
        configDTO.setProtocol("ftp");
        if("ftp".equals(configDTO.getProtocol())) {
            FTPClient ftp = new FTPClient();
            ftp.connect(configDTO.getIp(), configDTO.getPort());
            ftp.login(configDTO.getUsername(), configDTO.getPassword());
            int reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                throw new RuntimeException("连接失败：replyCode=" + reply);
            }
            ftp.disconnect();
        } else if("sftp".equals(configDTO.getProtocol())){
            JSch jsch = new JSch();
            Session session = jsch.getSession(configDTO.getUsername(),configDTO.getIp(),configDTO.getPort());
            session.setPassword(configDTO.getPassword());
            Properties config = new Properties();
            config.setProperty("StrictHostKeyChecking","no");
            session.setConfig(config);
            session.connect();
            Channel channel = session.openChannel("sftp");
            channel.connect();
            channel.disconnect();
            session.disconnect();
        }
    }
}
